package com.javaweb.dao.impl;

import com.javaweb.dao.CategoryDao;
import com.javaweb.model.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Repository
public class CategoryDaoImpl implements CategoryDao {
    @Autowired
    JdbcTemplate jdbcTemplate ;

    @Override
    public int insert(Category category) {
        String sql = "INSERT INTO tb_category (name, `order`, parent_id, create_time, update_time)" +
                " VALUES (?,?,?,?,?)" ;

        Object[] args = new Object[]{
                category.getName(),
                category.getOrder(),
                category.getParentId(),
                new java.sql.Date(new Date().getTime()),
                new java.sql.Date(new Date().getTime())

        };

        return jdbcTemplate.update(sql,args);
    }

    @Override
    public int delete(Integer categoryId) {
        String sql = "delete from tb_category where id = ?" ;

        return jdbcTemplate.update(sql,new Object[]{categoryId});
    }

    @Override
    public List<Category> list() {
        String sql = "select * from tb_category";
        return jdbcTemplate.query(sql,rs->{
            List<Category> list = new ArrayList<>();
            while (rs.next()){
                Category category = new Category();
                category.setId(rs.getInt("id"));
                category.setName(rs.getString("name"));
                category.setOrder(rs.getInt("order"));
                category.setParentId(rs.getInt("parent_id"));
                category.setCreateTime(rs.getDate("create_time"));
                category.setUpdateTime(rs.getDate("update_time"));
                list.add(category);
            }
            return list;
        });
    }
}
